package com.hatricks.is.base.refrence;

import java.lang.ref.WeakReference;
import java.util.HashMap;
import java.util.Map;

/**
 * @packageName: com.hatricks.base.refrence
 * @className: ReferenceExample
 * @author: yanyuhui y568821795@outlook.com
 * @date: 2023/7/27 20:40
 * @description: 引用示例
 */
public class ReferenceExample {

    public static void main(String[] args) {
        // 创建一个弱引用的缓存
        Map<String, WeakReference<ExpensiveObject>> cache = new HashMap<>();

        // 添加对象到缓存
        ExpensiveObject obj1 = new ExpensiveObject("Object 1");
        ExpensiveObject obj2 = new ExpensiveObject("Object 2");
        cache.put("obj1", new WeakReference<>(obj1));
        cache.put("obj2", new WeakReference<>(obj2));

        // 从缓存获取对象
        ExpensiveObject cachedObj1 = cache.get("obj1").get();
        ExpensiveObject cachedObj2 = cache.get("obj2").get();

        // 使用缓存中的对象
        System.out.println("Object 1 from cache: " + cachedObj1); // Object 1
        System.out.println("Object 2 from cache: " + cachedObj2); // Object 2

        // 现在，手动将obj1设置为null，让它只有弱引用引用
        obj1 = null;
        obj2 = null;
        // 强制进行垃圾回收
        System.gc();
        System.gc();
        System.gc();

        // 由于obj1只有弱引用引用，可能已经被回收
        cachedObj1 = cache.get("obj1").get();
        cachedObj2 = cache.get("obj2").get();
        System.out.println("Object 1 from cache after GC: " + cachedObj1); // 可能为null
        System.out.println("Object 2 from cache: " + cachedObj2); // Object 2
    }

    // 一个昂贵的对象，用于示例
    static class ExpensiveObject {
        private String name;

        public ExpensiveObject(String name) {
            this.name = name;
        }

        @Override
        public String toString() {
            return name;
        }
    }


}
